/*
	Powered CMSDream © All rights reserved.
	@By GhostWei
	@Email: ghostwei#gmail.com
*/
var Comment = {};
Comment.PostID = 0;
Comment.Id = 'comment';
Comment.URL = '';
Comment.Data = [];
Comment.splitPage = 3;
Comment.Posting = false;
Comment.ListTag = "\
	<dl id=\"comment-id-[$ID]\" onmouseover=\"this.style.background=\\'#ffffff\\';\" onmouseout=\"this.style.background=\\'none\\';\">\
		<dt><img width=\"64\" src=\"http://static.ghostwei.com/img/avatar.png\" /></dt>\
		<dd>\
			<div id=\"comment-author-[$ID]\" class=\"meta\"><strong><a href=\"[$url]\" target=\"_blank\">[$author]</a></strong></div>\
			<div class=\"body\">\
				<div id=\"comment-content-[$ID]\">[$content]</div>\
				<code class=\"b\"><a href=\"#respond\" onclick=\"Comment.Reply([$ID],[$pid])\">回复</a> 发表于：[$time]</code>\
			</div>\
			{children}\
		</dd>\
	</dl>\
";

Comment.Reply = function(cid,pid){
	try{
		this.E('input','parent').val(pid);
		var self = this;
		setTimeout(function(){self.E('textarea','comment').focus();},50);
		var c = $('#'+this.Id+'-content-'+cid).text();
		var a = $('#'+this.Id+'-author-'+cid).text();
		$('#'+this.Id+'-quote').text('['+a+']-'+c);
	}catch(e){}
};

Comment.E = function(type, name){
	return $("form#"+this.Id+"-form "+type+"[name="+name+"]");
};

Comment.replaceTags = function(c){
	if(typeof(c)!='object')return '';
	var s = this.ListTag;
	s = s.replace(/\[\$([\w]+)\]/g,"'+c.$1+'");
	return eval("'"+s+"'");
};

Comment.reloaceLoop = function(D){
	var s = '';
	for(var i=0;i<D.length;i++){
		var v = this.replaceTags(D[i]);
		if(D[i].children==null){
			v = v.replace("{children}", "");
		}else{
			v = v.replace("{children}", "<div class=\"children\">" + this.reloaceLoop(D[i].children) + "<div>");
		}
		s += v;
	}
	return s;
};

Comment.initData = function(json, hash){
	var s = this.reloaceLoop(json.Data);
	$('#' + this.Id + '-list').html(s);

	var pageSize = parseInt(json.PageSize);
	var Total = parseInt(json.Total);
	var currentPage = parseInt(json.CurrentPage);	
	var totalPage = parseInt(Total % pageSize) == 0 ? parseInt(Total / pageSize) : parseInt(Total / pageSize) + 1;	
	this.constructPaged(totalPage, currentPage);			
	if(hash) window.location.hash = 'comment';
};

Comment.Load = function(pid){
	if(typeof(pid)=='undefined') pid = 1;
	if(typeof(this.Data[pid])!='undefined'){;
		this.initData(this.Data[pid], true)
	} else {
		var self = this;
		$('#' + this.Id + '-list').html("<p class=\"loading\">正在加载评论，请稍后...</p>");
		$.ajax({type: "POST",url: self.URL,data: "p=" + this.PostID + "&g=" + pid + '&o=json',success: function(data){
			try{
				eval("var json = " + data);
				self.Data[pid] = json;
				self.initData(self.Data[pid], (pid>1 ? true : false));
			}catch(e){
				$('#' + self.Id + '-list').html("<p class=\"error\">数据加载错误 ！ [ <a href=\"javascript:Comment.Load()\">重试</a> ]</p>");
			}
		}});
	}
};

Comment.constructPaged = function(totalPage, currentPage){
	if(totalPage<=1) {
		$('#' + this.Id + '-page').html("");
		return false;
	}
	
	var _from = Math.max(1, currentPage - this.splitPage);
	var _to = Math.min(totalPage, currentPage + this.splitPage);
	
	var s = '';
	s += '<ul class="paged">';
	if (currentPage > 1) {
		s += '<li><a title="上一页" href="javascript:Comment.Load(' + (currentPage - 1) + ');">Previous</a></li>';
	}

	if (_from > 1) {
		s += '<li><a href="javascript:Comment.Load(1);">1</a></li>';
		if (_from > 2) {
			s += '<li>...</li>';
		}
	}
	
	for (var i = _from; i <= _to; i++) {
		s += '<li' + (i != currentPage ? '' : ' class="current"') + '>';
		s += '<a href="javascript:Comment.Load(' + i + ');">' + i + '</a></li>';
	}

	if (_to < currentPage) {
		if (_to < currentPage - 1) {
			s += '<li>...</li>';
		}
		s += '<li><a href="javascript:Comment.Load(' + totalPage + ');">' + totalPage + '</a></li>';
	}

	if (currentPage < totalPage) {
		s += '<li><a title="下一页" href="javascript:Comment.Load(' + (currentPage + 1) + ');">Next</a></li>';
	}
	
	s += '</ul>';
	$('#' + this.Id + '-page').html(s);
};

Comment.showCode = function(force){
	var img = $('#' + this.Id + '-code');
	if(force || img.attr('showed')!='true'){
		img.attr('src', '/verify-code?r='+Math.random().toString().replace('.','_'));
		img.attr('showed', 'true');
	}
};

Comment.Submit = function(){
	if(this.Posting) return false;
	var e = null;
	if(this.E('input','logged_user_id').val()=='0'){
		e = this.E('input','email');
		if(!/^([a-zA-Z0-9\._-]+)@([a-zA-Z0-9_-]+)\.([a-zA-Z0-9\._-]+)$/.test(e.val())) {
			alert('请输入正确的Email地址！\n电子邮件地址不会被公开。');
			e.focus();
			return false;
		}
		e = this.E('input','username');
		if(e.val().replace(/(^\s*)|(\s*$)/g, "")=='') {
			alert('请输入您的姓名！');
			e.focus();
			return false;
		}
		if(document.getElementById('vcode')) {
			e = this.E('input','vcode');
			if(!/^([0-9a-zA-Z]{6})$/.test(e.val())) {
				alert('请输入验证码！\n如果看不清图片可点击图片重新加载。');
				e.focus();
				return false;
			}
		}
		e = this.E('input','url');
		if(e.val() != '' && !/^(http|https)\:\/\/([\w\.\/\-]{5,})/ig.test(e.val())) {
			alert('请输入正确的网站地址！\n如果您没有网站地址，此项可以留空。');
			e.focus();
			return false;
		}
	}
	e = this.E('textarea','comment');
	if(e.val().replace(/(^\s*)|(\s*$)/g, "")=='') {
		alert('请输入评论内容！');
		e.focus();
		return false;
	}
	var self = this;
	this.Posting = true;
	$.ajax({type:"POST",url:self.URL,data:$('form#'+self.Id+'-form').serialize() + '&submit=' + self.PostID + '&o=json',success:function(data){
		self.Posting = false;
		try{
			eval("var json = " + data);
			var msg = json.Message;
			if(/^[\d]+$/i.test(msg)) {
				self.E('textarea','comment').val('');
				alert('评论发表成功，感谢您的参与！');
				$('#' + self.Id + '-list').html("<p class=\"loading\">正在加载评论，请稍后...</p>");
				self.Data = [];
				self.Data[1] = json.List;
				self.initData(self.Data[1], true);
			} else {
				alert(msg);
			}
		}catch(e){
		}
	}});
	return false;
};

